package com.weiyirong99.crm.app.ui;

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.CallLog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseActivity;
import com.weiyirong99.crm.app.bean.MessageEvent;
import com.weiyirong99.crm.app.bean.PhoneBean;
import com.weiyirong99.crm.app.bean.PhoneListBean;
import com.weiyirong99.crm.app.model.TabEntity;
import com.weiyirong99.crm.app.server.WorkAloneService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {

    private View view;
    private FrameLayout purchaserHomeFl;
    private CommonTabLayout tablayoutStl;
    private String[] mTitles = {"首页", "拨号", "我的"};
    //    private String[] mTitles = {"我的客户", "个人中心"};
    private int[] mIconUnselectIds = {R.drawable.home, R.drawable.nav_activity, R.drawable.mine};
    //    private int[] mIconUnselectIds = {R.drawable.nav_activity, R.drawable.mine};
    private int[] mIconSelectIds = {R.drawable.home1, R.drawable.nav_activity_select, R.drawable.mine_select};
    //    private int[] mIconSelectIds = {R.drawable.nav_activity_select, R.drawable.mine_select};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ArrayList<Fragment> mFragments;
    private FragmentManager mFragmentManager;
    private HomeFragment homeFragment;
    private PhoneFragment mPhoneFragment;
    private MyFragment myFragment;
    private long startTime;
    private WorkAloneService.MyBinder binder = null;
    private WorkAloneService mWorkAloneService;
    private boolean mBound = false;
    private static final int PERMISSION_REQUEST_CODE = 1;
    private ArrayList<PhoneBean> list = new ArrayList<PhoneBean>();

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG},
                    PERMISSION_REQUEST_CODE);
        } else {
            // 已经拥有权限，直接查询通话记录
            new Thread(new Runnable() {
                @Override
                public void run() {
                    queryCallLog();
                }
            }).start();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限，查询通话记录
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        queryCallLog();
                    }
                }).start();
            } else {
                // 用户拒绝了权限，做相应处理
            }
        }
    }

    private void queryCallLog() {
        if (list.size() > 0) {
            list.clear();
        }

        // 获取当前时间的毫秒数
        long currentTime = System.currentTimeMillis();

        // 计算一周前的时间
        long oneWeekAgo = currentTime - (7 * 24 * 60 * 60 * 1000);

        // 查询条件：通话时间大于等于一周前的时间
        String selection = CallLog.Calls.DATE + " >= ?";

        // 查询参数：一周前的时间
        String[] selectionArgs = {String.valueOf(oneWeekAgo)};

        // 按照通话时间倒序排序
        String sortOrder = CallLog.Calls.DATE + " DESC";

        // 执行查询
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(
                CallLog.Calls.CONTENT_URI,
                new String[]{
                        CallLog.Calls.CACHED_NAME,  //姓名
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.DURATION,   //通话时长
                },
                selection,
                selectionArgs,
                sortOrder
        );

        // 遍历查询结果
        if (cursor != null && cursor.moveToFirst()) {
            int mobile = cursor.getColumnIndex(CallLog.Calls.NUMBER);
            int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
            int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
            int calledAt = cursor.getColumnIndex(CallLog.Calls.DATE);
            do {

                String phoneNumber = cursor.getString(mobile);
                String typeString = "";
                String durationSting = cursor.getString(duration);
                String calledAtString = cursor.getString(calledAt);
                int callTypeCode = cursor.getInt(type);
                switch (callTypeCode) {
                    case CallLog.Calls.INCOMING_TYPE:
                        typeString = "IN";
                        Log.e("WG", "queryCallLog:  呼入");
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        typeString = "OUT";
                        Log.e("WG", "queryCallLog:  呼出");
                        break;
                    case CallLog.Calls.MISSED_TYPE:
                        calledAtString = "0";
                        typeString = "IN";
                        Log.e("WG", "queryCallLog:  未接");
                        break;
                    default:
                        //其他类型的，例如新增号码等记录不算进通话记录里，直接跳过
                        continue;
                }
                PhoneBean phoneBean = new PhoneBean();
                phoneBean.setMobile(phoneNumber);
                phoneBean.setType(typeString);
                phoneBean.setDuration(Integer.parseInt(durationSting));
                phoneBean.setCalledAt(Long.parseLong(calledAtString));

                // 处理手机号码
                list.add(phoneBean);
            } while (cursor.moveToNext());
            cursor.close();
//            String s = ;
//            Log.e("WG"," 有多少个 ："+ s);
            setPhone();
        }
    }

    private void setPhone() {

        long id = MMKV.defaultMMKV().decodeInt("companyId");
        int customer_id = getIntent().getIntExtra("customer_id", 0);
//        long customerid = MMKV.defaultMMKV().decodeInt("customerid");
        String url = Url.BaseUrl + "/api/company/" + id + "/user-call-log";
//        Map<String, Object> dataMap = new HashMap<>();
////        dataMap.put("group", "1");
//        dataMap.put("keyword", name);
//        JSONObject jsonObject = new JSONObject(dataMap);
        OkGo.<String>post(url)
                .tag(MainActivity.this)
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                .upJson(new Gson().toJson(list))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("WG", "onSuccess: " + response.body());
                        if (response.code() == 200) {

                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String message = jsonObject.getString("message");
                                Log.e("wg", "error: " + message);
                                ts(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");
                        ts(response.message());
                    }
                });

    }

    @Override
    public void initView() {
        view = (View) findViewById(R.id.view);
        purchaserHomeFl = (FrameLayout) findViewById(R.id.purchaser_home_fl);
        tablayoutStl = (CommonTabLayout) findViewById(R.id.tablayout_stl);

    }

    private void bindToService() {
        Intent bindIntent = new Intent(this, WorkAloneService.class);
        bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (WorkAloneService.MyBinder) service;
            mWorkAloneService = binder.getService();
            mWorkAloneService.setCallback((what, data) -> EventBus.getDefault().postSticky(new MessageEvent(what, data)));
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    @Override
    public void initParms(Bundle parms) {
        mFragments = new ArrayList<>();
        homeFragment = new HomeFragment();
        mPhoneFragment = new PhoneFragment();
        myFragment = new MyFragment();

        if (mFragments.size() <= 0) {
            mFragments.add(homeFragment);
            mFragments.add(mPhoneFragment);
            mFragments.add(myFragment);
        }

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        tablayoutStl.setTabData(mTabEntities, getActivity(), R.id.purchaser_home_fl, mFragments);
        select(0);
        bindToService();
    }

    /**
     * 选中第i个Tab时的处理
     *
     * @param i
     */
    public void select(int i) {
        // 得到Fragment管理器以及事务
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragment(transaction);
        switch (i) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                } else {
                    transaction.show(homeFragment);
                }
                break;
            case 1:
                if (mPhoneFragment == null) {
                    mPhoneFragment = new PhoneFragment();
                } else {
                    transaction.show(mPhoneFragment);
                }
                break;
            case 2:
                if (myFragment == null) {
                    myFragment = new MyFragment();
                } else {
                    transaction.show(myFragment);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }

    /**
     * 只要fragment不为空，便一律隐藏
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (mPhoneFragment != null) {
            transaction.hide(mPhoneFragment);
        }
        if (myFragment != null) {
            transaction.hide(myFragment);
        }
    }

    @Override
    public BaseActivity getActivity() {
        return MainActivity.this;
    }

    //解决的fragment 页面覆盖的问题
    @Override
    protected void onSaveInstanceState(@NonNull @NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - startTime) >= 2000) {
            Toast.makeText(this, "再返回一次退出应用", Toast.LENGTH_SHORT).show();
//            ToastUtils.showShort(R.string.press_again_exit);
            startTime = currentTime;
        } else {
            moveTaskToBack(true);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        int what = event.getWhat();
        switch (what) {
            case 0:
                String s = (String) event.getData();
                ts(s);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }
}